package cn.net.shuxing.yifu.common.service;

import cn.net.shuxing.yifu.common.bean.CityAgentCommission;
import cn.net.shuxing.yifu.common.bean.DeclarationForm;
import cn.net.shuxing.yifu.common.bean.SysUser;
import cn.net.shuxing.yifu.common.dto.BaseDto;
import cn.net.shuxing.yifu.common.dto.CodeConst;
import cn.net.shuxing.yifu.common.mapper.CityAgentCommissionMapper;
import cn.net.shuxing.yifu.common.mapper.DeclarationFormMapper;
import cn.net.shuxing.yifu.common.mapper.SysUserMapper;
import cn.net.shuxing.yifu.common.util.DateUtil;
import cn.net.shuxing.yifu.common.util.MD5Util;
import cn.net.shuxing.yifu.mysiteforme.admin.base.MySysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.util.StringUtil;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class DeclarationFormService{


    @Autowired
    DeclarationFormMapper declarationFormMapper;

    @Autowired
    SysUserMapper sysUserMapper;

    @Autowired
    CityAgentCommissionMapper cityAgentCommissionMapper;

    //新用户姓名、手机号、转币量、售卖单价（CNY）、结算限期（输入天数，最高输入7天，最低1天）
    public BaseDto add(String nickName, String tel, BigDecimal coinNum, BigDecimal unitPrice,BigDecimal publicPrice, Integer limitDay){
        BaseDto baseDto = new BaseDto();
        Long userId = MySysUser.id();
        DeclarationForm declarationForm = new DeclarationForm();
        declarationForm.setUserId(userId);
        declarationForm.setCoinNum(coinNum);
        declarationForm.setUnitPrice(unitPrice);
        declarationForm.setLimitDay(limitDay);
        declarationForm.setNickName(nickName);
        declarationForm.setPublicPrice(publicPrice);
        declarationForm.setTel(tel);
        declarationForm.setCreateTime(LocalDateTime.now().toString());
        declarationForm.setComm(getShareholderComm(userId,publicPrice,coinNum));
        //获取保单id
        declarationForm.setFormId(getFormId(userId));

        Integer m = declarationFormMapper.insertSelective(declarationForm);
        if(m > 0){
            baseDto.setCode(CodeConst.OK);
            baseDto.setData("添加成功");
        }else{
            baseDto.setCode(CodeConst.ERROR);
            baseDto.setData("添加失败");
        }
        return baseDto;
    }

    public String getFormId(Long userId){
        //保单id组成：兼职股东userId+当前时间
        String formId = "" + userId + System.currentTimeMillis();
        return formId;
    }

    public List<DeclarationForm> selectList(Integer startPageOn,Integer pageSize,Long userId,Integer dealStatus){
        List<DeclarationForm> list = declarationFormMapper.selectList(startPageOn,pageSize,userId,dealStatus);
        if(null != list && list.size()>0){
            for (DeclarationForm df:list) {
                if(df.getDealStatus() == 1){
                    df.setDealStatusStr("未处理");
                }else if(df.getDealStatus() == 2){
                    df.setDealStatusStr("已充值");
                }else if(df.getDealStatus() == 3){
                    df.setDealStatusStr("已拒绝");
                }else if(df.getDealStatus() == 4){
                    df.setDealStatusStr("待结算");
                }else{
                    df.setDealStatusStr("已结算");
                }
                if(StringUtil.isNotEmpty(df.getCreateTime())){
                    df.setCreateTime(df.getCreateTime().substring(0,df.getCreateTime().length() - 2));
                }

                SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date= null;
                try {
                    date = sdf.parse(df.getCreateTime());
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(date);
                    calendar.add(Calendar.DATE, df.getLimitDay());
                    date = calendar.getTime();
                    String limitTime = sdf.format(date);
                    df.setLimitTime(limitTime);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        }
        return list;
    }

    /**
     * 报单充值
     * @return
     */
    public BaseDto formDeposit(String password,Long id){
        BaseDto baseDto = new BaseDto();
        //获取平台管理员信息
        SysUser sysUser = sysUserMapper.selectAdmin();
        if(sysUser != null){
            if (!sysUser.getPassword().equals(MD5Util.md5(password)))
            {
                return BaseDto.error("管理员登录密码输入错误");
            }
            //证明是管理员
            if(MD5Util.md5(password).equals(sysUser.getPassword())){
                //获取转币量
                DeclarationForm declarationForm = declarationFormMapper.selectById(id);
                //转币量大于0
                if (null != declarationForm && (declarationForm.getCoinNum()).compareTo(new BigDecimal(0)) == 1) {
                    //todo:进行充值操作


                    //充值成功,修改状态
                    declarationForm.setDealStatus(2);//已充值
                    declarationFormMapper.updateByPrimaryKeySelective(declarationForm);
                    baseDto.setData("充值成功");
                }
            }
        }
        return baseDto;
    }

    /**
     * 报单拒绝
     * @return
     */
    public BaseDto formRefuse(Long id){
        BaseDto baseDto = new BaseDto();
        DeclarationForm declarationForm = new DeclarationForm();
        declarationForm.setId(id);
        declarationForm.setDealStatus(3);//已拒绝
        declarationFormMapper.updateByPrimaryKeySelective(declarationForm);
        baseDto.setData("审核拒绝");
        return baseDto;
    }


    public List<DeclarationForm> commList(Integer startPageOn, Integer pageSize,Long userId) {
        return declarationFormMapper.commList(startPageOn, pageSize, userId);
    }

    /**
     * 获取报单详情
     * @param id
     * @return
     */
    public BaseDto detail(Long id){
        BaseDto baseDto = new BaseDto();
        DeclarationForm declarationForm = declarationFormMapper.selectById(id);
        baseDto.setData(declarationForm);
        return baseDto;
    }

    /**
     * 结算佣金
     * @return
     */
    public BaseDto balanceComm(Long id){
        BaseDto baseDto = new BaseDto();
        DeclarationForm declarationForm = declarationFormMapper.selectById(id);
        if(null != declarationForm && declarationForm.getComm().compareTo(BigDecimal.ZERO)>0){
            CityAgentCommission cityAgentCommission = cityAgentCommissionMapper.selectByUserId(declarationForm.getUserId());
            if(null != cityAgentCommission){
                //更新报单状态
                int m = declarationFormMapper.updateDealStatus(id,5);
                if(m>0) {
                    BigDecimal cumulativeComm = cityAgentCommission.getCumulativeComm().add(declarationForm.getComm());
                    //更新用户累积佣金
                    cityAgentCommission.setCumulativeComm(cumulativeComm);
                    cityAgentCommissionMapper.updateCumulativeComm(cityAgentCommission.getUserId(),cumulativeComm);
                    baseDto.setData("结算成功");
                }
            }
        }
        return baseDto;
    }



    /**
     * 获取兼职股东的结算佣金
     * @param userId
     * @return
     */
    public BigDecimal getShareholderComm(Long userId,BigDecimal publicPrice,BigDecimal coinNum){
        BigDecimal comm = new BigDecimal(0);
        DeclarationForm declarationForm = declarationFormMapper.selectById(userId);
        if(null != declarationForm){
            //获取兼职股东佣金比例
            CityAgentCommission cityAgentCommission = cityAgentCommissionMapper.selectByUserId(declarationForm.getUserId());
            if(null != cityAgentCommission){
                //佣金比例
                BigDecimal commRate = cityAgentCommission.getCommRate();
                if(commRate.compareTo(BigDecimal.ZERO)>0){
                    //计算结算佣金
                    comm = coinNum.multiply(new BigDecimal(0.05)).multiply(publicPrice).multiply(commRate);
                }
            }
        }
        return comm;
    }




}
